package pl.drypisy;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Scanner;

import android.util.Log;

/** 
 * @author Marcin Pilat
 * @version 1.0
 */
public class FTPAdapter {
	
	private URLConnection client;
	//private final String HOST = "ftp.drivehq.com";
	//private final String USER = "frexus";
	//private final String PASS = "qwert123";
	private final String HOST = "geopoint.ugu.pl";
	private final String USER = "geopoint.ugu.pl";
	private final String PASS = "qwert123";
	private final String FOLDER = "";//"projekt/";
	private final String LIST_FILE = "list.txt";
	private ArrayList<RouteData> routeList = new ArrayList<RouteData>();
	
	/**
	 * Connect to server by FTP and download list with maps 
	 * @return array with list of names of routes
	 */
	public synchronized ArrayList<RouteData> downloadList(){
		StringBuffer fileContent = new StringBuffer();
		connect(FOLDER+LIST_FILE);
	    try{
		      InputStream is = client.getInputStream();
		      Scanner read = new Scanner(is);
		      
		      while (read.hasNextLine()){
		    	  fileContent.append(read.nextLine() + ";");
		      }
		      is.close ();
		      
		      readList(fileContent.toString());
	    }
	    catch(Exception e) {
	    	//ArrayList<RouteData> tmp = new ArrayList<RouteData>();
	    	//tmp.add(e.toString());
		    Log.d("FTP1", e.toString());
		    //return tmp;
	    }
	    return routeList;
	  }
		
	/**
	 * @param routeName name of requested route
	 * @return InputStream to xml file which contains route from parameter
	 */
	public synchronized InputStream downloadRoute(String routeName){
		
		connect(FOLDER+routeName+".xml");
	    try{
		      InputStream is = client.getInputStream();
		      Log.d("FTP_ROUTE", "Połączony");	
		      return is;
	    }
	    catch(Exception e) {
	    	Log.d("FTP_ROUTE",e.toString());
	      return null;
	    }
	  }

	  // connecting with server and file
	  private synchronized boolean connect(String file){
	    try{

		    URL url = new URL("ftp://"+USER+":"+PASS+"@"+HOST+"/"+file);
		    client = url.openConnection();
	
		    return true;
	    }
	    catch(Exception e) {
		  Log.d("FTP2", e.toString());
	      return false;
	    }
	  }
	  
	  //Putting maps names to ArrayList of RouteData
	  private void readList(String list){
		  String [] tmp = list.toString().split(";");
		  int index=1;
		  //schema in list.txt: title,nr,about,date
		  for (int i = 0 ; i < tmp.length ; i=i+4){
			  //id,title,date,about
			  RouteData r=new RouteData(index++,tmp[i], tmp[i+3] ,tmp[i+2]);
			  routeList.add(r);
			  Log.d("ftp", r.toString());
		  }
	  }
}